<template>
	<view style="height: 100%;">
		<!-- <view class="" :style="{background:uiType == 'lexin'?'rgba(255, 255, 255, 0.99)':' rgba(0, 0, 0, 0.95)'}" -->
		<view v-if="callType=='FamilyCall'" class="navTitle" :style="{top:statusHeight+'px'}">{{device.deviceName}}</view>
		<view class="" :style="{background:'linear-gradient(180deg, #171a21 0%, #494951 100%);'}"
			style="width: 100%;height: 100%;position: fixed;">
			<view class="u-f-ajc imgV" @click="uiType == 'lexin' ? toLive() : answerClick()">
				<image class="img" v-show="imgLoaded" @load="onSuccessImg(alarmPic)" @error="imageError($event, 0)"
					:src="alarmPic" mode="aspectFit" />
				<image class="img" v-show="!imgLoaded" :src="defaultAlarmPic" mode="aspectFit" />
				<image class="replay" :src="replay" mode="" />
			</view>
			<!-- <view :style="{color:uiType == 'general'?'#fff':'#666'}" class="bottomV u-f-ajc u-f-c"> -->
			<view :style="{color:'#fff'}" class="bottomV u-f-ajc u-f-c">
				<view class="u-f-c u-f-ajc">
					<text v-if="callType == 'FamilyCall'" class="name">家人来电</text>
					<text v-else class="name">{{device.deviceName}}</text>
					<!-- <text>等待接听</text> -->
					<text>等待接听{{countDown}}s</text>
				</view>
				<view class="box">
					<view class="u-f-c u-f-ac" @click="closePopup(1)">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/hangUp.png" mode="" />
						<!-- <text>拒绝</text> -->
					</view>
					<view class="u-f-c u-f-ac" v-if="uiType == 'general'" @click="answerClick">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/answer.png" mode="" />
						<!-- <text>接听</text> -->
					</view>
					<view v-if="uiType == 'lexin'" class="u-f-c u-f-ac" @click="unlocking">
						<image class="icon" v-show="!openIng" src="https://statics.xmcsrv.net/weixin/opens.png"
							mode="" />
						<image class="icon" v-show="openIng" src="https://statics.xmcsrv.net/weixin/opens.gif"
							mode="" />
						<!-- <text>开锁{{countDown}}s</text> -->
					</view>
				</view>
				<!-- <view class="box lexin-box" v-if="uiType == 'lexin'"> -->
				<view class="box lexin-box" v-if="false">
					<view class="u-f-c u-f-ac" @click="cancelUnlock(1)">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/live/operation/cancel.png" mode="" />
						<text>取消</text>
					</view>
					<view class="u-f-c u-f-ac" @click="unlocking">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/live/operation/unlocking2.png"
							mode="" />
						<text>开锁{{countDown}}s</text>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="unlockDialog" type="dialog">
			<view class="form">
				<view class="u-f-ajc title">是否打开门锁？</view>
				<view class="u-f-r form-item">
					<view class="u-f-ajc cancel" @click="cancel()">取消</view>
					<view class="u-f-ajc conf" @click="confimeUnlock(1,'lexin',lastMsgTime)">确认</view>
				</view>
			</view>
		</uni-popup>
		<!-- <uni-popup ref="popup" class="popup" style="width: 100%;" :is-mask-click="false" maskBackgroundColor="rgba(0, 0, 0, 0.95)">
			<view class="u-f-ajc imgV">
				<image class="img" :src="alarmPic" mode="aspectFit"></image>
			</view>
			<view class="bottomV u-f-ajc u-f-c">
				<view class="u-f-c u-f-ajc">
					<text class="name">{{device.deviceName}}</text>
					<text>等待接听</text>
				</view>
				<view class="box">
					<view class="u-f-c u-f-ac" @click="closePopup">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/hangUp.png" mode=""></image>
						<text>拒绝</text>
					</view>
					<view class="u-f-c u-f-ac" @click="answerClick">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/answer.png" mode=""></image>
						<text>接听</text>
					</view>
				</view>
			</view>
		</uni-popup> -->
	</view>
</template>

<script>
	// import { getCurrentInstance, getCurrentScope } from "vue";
	const {
		calculateTimeDifference,
	} = require('@/utils/util.js');
	import deviceLogin from '@/utils/deviceLogin.js';
	export default {
		data() {
			return {
				deviceNo: '',
				device: {},
				AlarmID: '',
				alarmPic: '',
				defaultAlarmPic: 'https://statics.xmcsrv.net/weixin/previewBg.png',
				audioUrl: 'https://statics.xmcsrv.net/weixin/doorcall.wav',
				replay: 'https://statics.xmcsrv.net/weixin/replay.png',
				audioCtx: null,
				timerId: null,
				isHangUp: false,
				uiType: 'general',
				AlarmTime: '',
				countDown: 60,
				countsId: null,

				repetitionImg: 0,
				openIng: false, //开锁状态判断
				imgLoaded: false,
				tapType: 1,
				executeCallback: false, //是否执行mqtt消息回调避免重复执行
				callType:'FamilyCall',//DoorLockCall门铃来电  FamilyCall家人来电
				statusHeight:0
			};
		},
		onLoad(opt) {
			let res = JSON.parse(opt.message)
			this.device = JSON.parse(decodeURIComponent(opt.device))
			console.log('门铃来电=======', res);
			this.executeCallback = true
			uni.$on('onWebsocketMessage', this.getDoorCallMqttInfoCallback)
			if (Object.keys(res).length > 0) {
				this.deviceNo = res.SerialNumber
				this.AlarmID = res.AlarmId
				this.AlarmTime = res.AlarmTime
				this.setDevice()
			}
			if(opt.type){
				this.callType = opt.type
			}
			console.log(this.deviceNo, this.AlarmID, this.AlarmTime)
			// 播放语音
			this.audioCtx = wx.createAudioContext('myAudio')
			this.audioCtx = wx.createInnerAudioContext({
				useWebAudioImplement: true
			})
			this.storgeAudio()
			this.audioCtx.src = this.audioUrl
			this.audioCtx.autoplay = true
			this.audioCtx.loop = true
			this.audioCtx.play()
			this.audioCtx.onPlay(() => {
				this.$logs({
					info: '音频开始播放',
					device: this.device
				})
			})
			this.audioCtx.onError((res) => {
				this.$logs({
					info: '音频播放错误',
					err: res,
					device: this.device
				})
			})
		},
		onShow() {
			this.repetitionImg = 0
			this.statusHeight = uni.getSystemInfoSync().statusBarHeight
		},
		onReady() {
			let currentPages = getCurrentPages()
			console.log('页面============1', currentPages);
		},
		onHide() {
			// this.audioCtx.play()
            if(this.audioCtx) this.audioCtx.pause();
            // this.audioCtx.src = ''
			// this.audioCtx.loop = false
            this.audioCtx = null
			clearInterval(this.countsId)
			this.countsId = null
			this.$logs({
				info: '门铃来电doorbellCall-onHide',
			})
		},
		onUnload() {
            // this.audioCtx.pause();
			// this.audioCtx.src = ''
            if(this.audioCtx) this.audioCtx.pause();
            this.audioCtx = null
			clearInterval(this.countsId)
			this.countsId = null;
			this.executeCallback = false;
			uni.$off('onWebsocketMessage', this.getDoorCallMqttInfoCallback)
			this.$logs({
				info: '门铃来电doorbellCall-onUnload',
			})
		},
		methods: {
			// mqtt接收
			getDoorCallMqttInfoCallback(res) {
				let info = JSON.parse(res)
				let page = getCurrentPages()
				let openDoorId = uni.getStorageSync('openDoorId')
				if (info.sn == this.deviceNo) {
					console.log(info.props, info.props[0].propValue.SerialNumber, '查看mqtt消息体')
					if (info.props[0].propValue.SerialNumber) {
						uni.setStorageSync('openDoorId', info.props[0].propValue.SerialNumber)
					}
					info.props.forEach(item => {
						if (item.propCode == "remoteUnlock" && openDoorId) {
							this.openIng = false
							uni.showToast({
								title: '开锁成功',
								success: () => {
									console.log(111, new Date().getTime())
									setTimeout(() => {
										this.closePopup(3)
										console.log(123, new Date().getTime())
									}, 1000)
								},
								fail: (err) => {
									console.log(err, 'showToast打开错误')
								}
							})
							this.$logs({
								info: '远程开锁成功',
								item: item
							})
						}
						if (item.propCode == "remoteUnlockFailed") {
							uni.showToast({
								title: '开锁失败',
								duration: 2000,
							})
							this.$logs({
								info: '远程开锁失败',
								item: item
							}, 'error')
						}
					})
				}
				// if(info.AlarmEvent === 'DoorLockOpen') {
				//     uni.showToast({
				//         title: '开锁成功'
				//     })
				//     setTimeout(() => {
				//         this.closePopup(1)
				//     }, 1000)
				// }
				// })
			},
			// 缓存音频文件
			storgeAudio() {
				const fs = wx.getFileSystemManager()
				const that = this
				let url = uni.getStorageSync('audioUrl')
				if (!url) {
					that.audioUrl = 'https://statics.xmcsrv.net/weixin/doorcall.wav'
					uni.downloadFile({
						url: 'https://statics.xmcsrv.net/weixin/doorcall.wav',
						success(res) {
							console.log('下载成功后的路径', res.tempFilePath)
							that.$logs({
								info: '下载文件成功',
								audioUrl: res.tempFilePath
							})
							fs.saveFile({
								tempFilePath: res.tempFilePath,
								success(result) {
									that.$logs({
										info: '保存文件成功',
										audioUrl: result.savedFilePath
									})
									console.log('保存成功的路径', result.savedFilePath)
									uni.setStorageSync('audioUrl', result.savedFilePath)
									// that.audioUrl = result.savedFilePath
								},
								fail(err2) {
									that.$logs({
										info: '保存文件失败',
										err: err2
									})
									console.log('保存失败1', err2)
								},
							})
						},
						fail(err) {
							that.$logs({
								info: '下载文件失败',
								err: err
							})
							console.log('下载失败1', err)
						},
					})
				} else {
					this.audioUrl = url
				}
				setTimeout(() => {
					console.log(this.audioUrl)
				}, 1000)
				fs.getSavedFileList({
					success(res) {
						console.log('缓存文件列表', res)
					}
				})
			},
			//打开
			openPopup() {
				// let time = this.uiType == 'lexin' ? 600000 : 15000
				let time = 600000
				this.countDown = calculateTimeDifference(this.AlarmTime, 1);
				console.log(this.countDown, '秒数')
				this.countsId = setInterval(() => {
					this.countDown--;
					if (this.countDown == 0) {
						clearInterval(this.countsId);
						this.closePopup(this.tapType)
						this.countDown == 60;
						// this.audioCtx.pause()
					}
				}, 1000)
				if (this.uiType == 'general') {
					this.timerId = setTimeout(() => {
						if (!this.isHangUp) {
							this.closePopup(2)
						}
						this.audioCtx.pause()
					}, 60000)
				}
			},
			//挂断
			closePopup(type) {
				console.log(this.audioCtx)
				this.audioCtx.pause()
                this.audioCtx = null
				clearTimeout(this.timerId)
				this.timerId = null
				clearInterval(this.countsId);
				this.countsId = null
				this.countDown = 60;
				if (type != 3) {
					uni.navigateBack()
				}
			},
			// 取消
			cancelUnlock() {
				this.closePopup(1)
				// this.audioCtx.pause()
				// this.audioCtx.src = ''
				this.$logs({
					info: '门铃来电挂断-cancelUnlock'
				})
			},
			toLive() {
				let data = this.device
				let url =
					`/jvss/pagesDevice/device/device-live/door-lock/live-lexin2?device=${encodeURIComponent(JSON.stringify(data))}&type=${'doorbell'}&AlarmTime=${this.AlarmTime}&operation=${'unlocking'}`
				this.tapType = 3
				if(this.callType == 'FamilyCall'){
					url = `/jvss/pagesDevice/device/device-live/door-lock/live-familyCall?device=${encodeURIComponent(JSON.stringify(data))}`
				}
				this.voesCallHangup(() => {
					uni.redirectTo({
						url: url
					})
				})
				// setTimeout(res => {
				// 	this.closePopup(1)
				// }, 200)
				this.$logs({
					info: '门铃来电接听-toLive',
					device: this.device,
				})
			},
			unlocking() {
				// this.getLogin()
				this.$refs.unlockDialog.open();
			},
			confimeUnlock() {
				this.cancel();
				this.openIng = true
				let data = {
					encryptType: 'DISABLE',
					LoginType: 'DVRIP-Web',
					UserName: this.device.devUserName,
					PassWord: this.device.devPassWord,
					Name: 'generalinfo',
					KeepaliveTime: 20
				};
				if (this.device.adminToken) {
					data.LoginToken = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				let token = this.device.token
				getApp().globalData.api.deviceLogin(data, token, (result) => {
					uni.hideLoading();
					if (result.data.code === 2000) {
						let Ret = result.data.data.Ret
						if (Ret === 100 || Ret === 104) {
							this.getUnlock()
						} else if (Ret === 137) {
							uni.showToast({
								title: getApp().globalData.errCodeMsg.RetCodeMsg[Ret] || result.data
									.data.RetMsg,
								icon: "none"
							})
						}
						// 出错
						else {
							uni.showToast({
								title: getApp().globalData.errCodeMsg.RetCodeMsg[Ret] ||
									result.data.data.RetMsg,
								icon: "none"
							})
						}
					}
					// 4000 参数错误
					else if (result.data.code === 4000) {
						uni.showToast({
							title: result.data.msg,
							icon: 'none',
							success: (res) => {}
						});
					}
				});
			},
			// 取消开锁
			cancel() {
				this.$refs.unlockDialog.close()
			},
			getUnlock() {
				let token = this.device.token;
				let data = {
					sn: this.device.deviceNo,
					props: {
						"doorLock": {
							"remoteOneKeyUnlock": 1
						}
					}
				};
				getApp().globalData.api.remoteUnlock(data, token, (result) => {
					uni.hideLoading();
					if (result.Ret === 100) {
						// this.openIng = false
						// uni.showToast({
						// 	title: '开锁成功',
						// });
						// setTimeout(() => {
						// 	this.closePopup(1)
						// }, 500)
					} else {
						uni.showToast({
							title: '开锁失败',
							icon: 'error'
						});
					}
				});
			},
			//接听
			answerClick() {
				this.closePopup(3)
				let constant = getApp().globalData.constant;
				let LOCK = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK;
				let LOCK2 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK2;
				let LOCK3 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK3;
				let LOCK4 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK4;
				let LOCK5 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK5;
				let LOCK6 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK6;
				let LOCK7 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7;
				let LOCK8 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK8;
				let LOCK9 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK9;
				let LOCK10 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK10;
				let LOCK11 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK11;
				let LOCK12 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK12;
				let LOCK13 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK13;
				let LOCK14 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK14;
				let LOCK15 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK15;
				let LOCK16 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK16;
				let url = ''
				let data = this.device
				if(this.callType == 'FamilyCall'){
					url =
						`/jvss/pagesDevice/device/device-live/door-lock/live-familyCall?device=${encodeURIComponent(JSON.stringify(data))}`
				}else{
					if (data.parentPid === LOCK5 || data.parentPid == LOCK7 || data.parentPid == LOCK12) {
						url =
							`/jvss/pagesDevice/device/device-live/door-lock/live-lexin?device=${encodeURIComponent(JSON.stringify(data))}`
					} else if (data.pid == LOCK || data.pid == LOCK2 || data.pid == LOCK4 || data.pid == LOCK5 || data.pid ==
						LOCK7 || data.pid == LOCK9 || data.pid == LOCK10 || data.pid == LOCK11) {
						url =
							`/jvss/pagesDevice/device/device-live/door-lock/live1?device=${encodeURIComponent(JSON.stringify(data))}`
					} else {
						`/jvss/pagesDevice/device/device-live/live/live?device=${encodeURIComponent(JSON.stringify(data))}`
					}
				}
				this.voesCallHangup(() => {
                    setTimeout(() => {
                        uni.redirectTo({
                            url: url
                        })
                    }, 200)
				})
				this.$logs({
					info: '门铃来电接听-answerClick',
					device: this.device,
				})
			},
			// 接听的时候需要挂断云电话
			voesCallHangup(callback) {
				let token = this.device.token
				let data = {
					userId: uni.getStorageSync('userInfo').userId,
					sn: this.device.deviceNo
				}
				getApp().globalData.api.voesCallHangup(data, token, (result) => {
					if (typeof callback == 'function') {
						callback(result)
					}
					this.$logs({
						info: '接听的时候需要调用挂断云电话',
						data: data,
						result: result
					})
				});
			},
			//获取设备信息
			setDevice(e) {
				if (this.device.localUiKey == "ui_doorlock_home") {
					this.uiType = 'lexin'
				}
				this.openPopup()
				this.getDeviceToken([this.deviceNo])
			},
			//获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				getApp().globalData.api.getDeviceToken(data, (result) => {
					this.device.token = result[0].token;
					this.getDeviceStatus([result[0].token])
					this.getImgUrl([this.AlarmID], this.device.token)
				});
			},
			// 获取设备状态
			getDeviceStatus(tokenList) {
				const data = {
					token: tokenList
				};
				getApp().globalData.api.getDeviceStatus(data, (result) => {
					this.device.status = result[0]
				})
			},
			//获取图片
			getImgUrl(data, token) {
				getApp().globalData.api.getPicUrl(data, token, (result) => {
					let defaultImg = 'https://statics.xmcsrv.net/weixin/previewBg.png'
					this.alarmPic = result.length > 0 ? result[0].url : '';
				});
			},
			onSuccessImg(item) {
				this.imgLoaded = true
			},
			// 上报图片 错误处理
			imageError(e, index) {
				this.repetitionImg++;
				this.imgLoaded = false;
				this.alarmPic = '';
				if (this.repetitionImg < 6) {
					setTimeout(() => {
						this.getImgUrl([this.AlarmID], this.device.token)
					}, 1000)
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: rgba(0, 0, 0, 0.95)
	}
	.navTitle{
		position: absolute;
		left: 50rpx;
		top: 50rpx;
		z-index: 2;
		color: white;
		font-size: 30rpx;
		height: 100rpx;
		line-height: 100rpx;
	}

	.popup {
		/deep/ .uni-popup {
			z-index: 9999;
		}
	}

	.img {
		width: 90%;
		height: calc(100vh - 500rpx);
		position: fixed;
		top: 150rpx;
	}

	.replay {
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		top: 40%;
		margin-top: -50rpx;
		left: 50%;
		margin-left: -50rpx;
	}

	.bottomV {
		position: fixed;
		bottom: 80rpx;
		left: 0;
		right: 0;
		height: 220rpx;
		color: white;

		.name {
			font-size: 32rpx;
			width: 100%;
			text-align: center;
			word-break: break-all;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			text-overflow: ellipsis;
			overflow: hidden;
			margin-bottom: 10rpx;
		}

		.box {
			width: 80%;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.lexin-box {
			width: 100%;
			justify-content: space-around;
		}

		.icon {
			width: 120rpx;
			height: 120rpx;
		}
	}

	.form {
		background: white;
		padding: 40rpx 40rpx;
		border-radius: 40rpx;

		.title {
			font-size: 34rpx;
			font-weight: bold;
			line-height: 49rpx;
			color: #464646;
		}

		.form-item {
			margin-top: 80rpx;

			.cancel {
				background: #F6F7FB;
				color: #000000;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
			}

			.conf {
				margin-left: 20rpx;
				background: #FF0025;
				color: #ffffff;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
			}
		}
	}
</style>
